package com.xjscrm.server.service.soptask.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.grouppull.GroupPullData;
import com.xjscrm.common.vo.grouppull.GroupPullMsgData;
import com.xjscrm.common.vo.sop.NewCustomerTigger;
import com.xjscrm.common.vo.sop.PlanData;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.PlanDataTools;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.grouppull.GroupPullDataService;
import com.xjscrm.server.service.soptask.SopJobMsgService;
import com.xjscrm.server.service.soptask.SopJobNewCustomerService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 增加新客户SOP任务
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class SopJobNewCustomerServiceImpl implements SopJobNewCustomerService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SopTaskDeviceMapper sopTaskDeviceMapper;
    @Autowired
    private SopTaskMapper sopTaskMapper;
    @Autowired
    private SopJobMapper sopJobMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private GroupPullDataService groupPullDataService;
    @Autowired
    private SopJobMsgService sopJobMsgService;
    @Autowired
    private SopTemplateMapper sopTemplateMapper;

    /**
     * 添加SOP任务-增加新客户
     *
     * @param wwCustomer 新客户对象
     * @return 实例对象
     */
    @Async("taskExecutorForXxJob")
    public void addSopJobByNewCustomer(WwCustomer wwCustomer, Device device) {
        if (wwCustomer == null) {
            return;
        }
        if (device == null) {
            return;
        }

        //查询该机器人配置的关键词拉群列表
        List<SopTaskDevice> sopTaskDeviceList = sopTaskDeviceMapper.selectByDeivceUniqueIdAndType(device.getDeviceUniqueId(), 2, device.getMerId());
        if (sopTaskDeviceList == null || sopTaskDeviceList.size() == 0) {
            return;
        }

        //查询符合条件的任意一个新客SOP方案(新会员SOP只触发一个)
        SopTask sopTask = verifyNewCustomer(sopTaskDeviceList, wwCustomer);
        if (sopTask != null) {

            if(sopTask.getTeaplateId() == null){
                return;
            }

            SopTemplate sopTemplate = sopTemplateMapper.selectById(sopTask.getTeaplateId());
            if(sopTemplate == null){
                return;
            }

            String planDatas = sopTemplate.getPlanDatas();
            if (StringUtils.isBlank(planDatas)) {
                return;
            }

            List<PlanData> planDataList = JSONObject.parseArray(planDatas, PlanData.class);
            if (planDataList == null || planDataList.size() == 0) {
                return;
            }

            //当前时间
            int now = DateUtil.getTime();

            //计算发送时间
            Integer sendTime = PlanDataTools.getSendTime(null, planDataList.get(0));

            //保存SopJob
            SopJob sopJob = new SopJob();
            sopJob.setId(IdWorker.getId());
            sopJob.setMerId(sopTask.getMerId());
            sopJob.setTaskId(sopTask.getId());
            sopJob.setName(sopTask.getName());
            sopJob.setStatus(1);
            sopJob.setType(sopTask.getType());
            sopJob.setTeaplateId(sopTask.getTeaplateId());
            sopJob.setTrigger(sopTask.getTrigger());
            sopJob.setPlanDatas(sopTemplate.getPlanDatas());
            sopJob.setWxid(wwCustomer.getWxid());
            sopJob.setDeviceUniqueId(device.getDeviceUniqueId());
            sopJob.setDeviceId(device.getDeviceId());
            sopJob.setFirstTime(sendTime);
            sopJob.setNextTime(sendTime);
            sopJob.setPlanDatasNextIndex(0);
            sopJob.setWxidType(0);//类型（0-客户;1-群）
            sopJob.setCreateTime(now);
            sopJob.setUpdateTime(now);
            sopJobMapper.insertSelective(sopJob);
        }
    }

    /**
     * 查找符合新客户运营的SOP任务，只查询符合条件的一个任务
     *
     * @param sopTaskDeviceList
     * @return null
     * @author jitwxs
     * @date 2024/4/22 12:00
     */
    private SopTask verifyNewCustomer(List<SopTaskDevice> sopTaskDeviceList, WwCustomer wwCustomer) {
        //新客SOP任务
        SopTask sopTask = null;
        //条件验证
        for (SopTaskDevice sopTaskDevice : sopTaskDeviceList) {
            try {
                sopTask = sopTaskMapper.selectById(sopTaskDevice.getTaskId());
                if (sopTask != null && sopTask.getStatus().intValue() == 1) {
                    NewCustomerTigger newCustomerTigger = JSONObject.parseObject(sopTask.getTrigger(), NewCustomerTigger.class);
                    if (newCustomerTigger != null) {
                        Integer triggerType = Tools.getInteger(newCustomerTigger.getTriggerType());
                        if (triggerType.intValue() == 0) {//直接触发，不需要验证
                            return sopTask;
                        } else if (triggerType.intValue() == 1) { //按照性别触发
                            Integer customerGenders = Tools.getInteger(newCustomerTigger.getCustomerGenders());
                            if (customerGenders.intValue() == Tools.getInteger(wwCustomer.getGender().intValue())) {
                                return sopTask;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

        return null;
    }

    /**
     * 自动处理手动SOP阶段性任务
     *
     * @param sopJob
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void autoStepSopJobByNewCustomer(SopJob sopJob) {

        if (sopJob == null) {
            return;
        }

        //获取该任务计划数据
        String planDatas = sopJob.getPlanDatas();
        if (StringUtils.isBlank(planDatas)) {
            return;
        }

        List<PlanData> planDataList = JSONObject.parseArray(planDatas, PlanData.class);
        if (planDataList == null || planDataList.size() == 0) {
            return;
        }

        int now = DateUtil.getTime();

        //获取当前阶段性数据的下标
        Integer planDatasNextIndex = Tools.getInteger(sopJob.getPlanDatasNextIndex());
        //如果下标已经超过数据的长度，则将任务修改成已完成
        if (planDatasNextIndex >= planDataList.size()) {
            sopJob.setStatus(2); //执行完成
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
            return;
        }

        //查询机器人
        WwDevice wwDevice = wwDeviceMapper.queryById(sopJob.getDeviceUniqueId());
        if (wwDevice == null) {
            sopJob.setStatus(0); //执行关闭
            sopJob.setUpdateTime(now);
            sopJob.setRemark("机器人未找到");
            sopJobMapper.updateStatusById(sopJob);
            return;
        }
        Device device = DeviceTools.transDevice(wwDevice);

        //查询会员
        WwCustomer wwCustomer = null;
        String sendNickname = null;
        if (Tools.getInteger(sopJob.getWxidType()).intValue() == 0) {
            wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(sopJob.getDeviceUniqueId(), sopJob.getWxid());
            if (wwCustomer == null) { //客户不存在，咋关闭
                sopJob.setStatus(0); //执行关闭
                sopJob.setUpdateTime(now);
                sopJob.setRemark("会员未找到");
                sopJobMapper.updateStatusById(sopJob);
                return;
            }

            //默认黑名单不通过
            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(sopJob.getMerId(), wwCustomer.getWxid());
            if (wwCustomerBlacklist != null) { //在黑名单中
                sopJob.setStatus(0); //执行关闭
                sopJob.setUpdateTime(now);
                sopJob.setRemark("黑名单会员");
                sopJobMapper.updateStatusById(sopJob);
                return;
            }

            //替换[称呼/昵称]变量，优先称呼，在昵称
            sendNickname = wwCustomer.getNickname();
            if (StringUtils.isBlank(sendNickname)) {
                sendNickname = wwCustomer.getName();
            }
        } else {//群发
            WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(sopJob.getDeviceUniqueId(), sopJob.getWxid());
            if (wwGroup == null) { //群不存在
                sopJob.setStatus(0); //执行关闭
                sopJob.setUpdateTime(now);
                sopJob.setRemark("群未找到");
                sopJobMapper.updateStatusById(sopJob);
                return;
            }
        }

        //本次的执行时间
        Integer sendTime_this = Tools.getInteger(sopJob.getNextTime());
        //获取当前需要发送的阶段性计划数据
        if(planDatasNextIndex < planDataList.size()){
            PlanData planData = planDataList.get(planDatasNextIndex);
            if (planData != null) {
                List<GroupPullData> groupPullDataList = planData.getMsgDataList();
                if (groupPullDataList != null) {
                    List<GroupPullMsgData> groupPullMsgDataList = groupPullDataService.handGroupPullData(sopJob.getMerId(), groupPullDataList, wwCustomer, device);
                    if (groupPullMsgDataList != null && groupPullMsgDataList.size() > 0) {
                        sopJobMsgService.addSopJobMsg(sopJob, sendTime_this, device, sopJob.getWxid(), sendNickname, groupPullMsgDataList);
                    }
                }
            }
        }

        //计算下一次发送时间
        if(planDatasNextIndex + 1 >= planDataList.size()){//没有下次，则直接修改成完成
            sopJob.setStatus(2);
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
        }else{
            Integer sendTime_next = PlanDataTools.getSendTime(sopJob.getFirstTime(), planDataList.get(planDatasNextIndex + 1));
            sopJob.setNextTime(sendTime_next);
            sopJob.setPlanDatasNextIndex(planDatasNextIndex + 1);
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
        }
    }


}
